import ScrollBarLayout from '@/components/ScrollBarLayout';
import Cls from 'classnames';
import { useEffect, useMemo, useState } from 'react';
import pageStyles from '@/common/pageLayout.less';
// import { ConditionManageContext } from '../mconfig/useManageContext';
import { DescriptionsType } from '@/components/DescriptionsType';
import { QuestionCircleOutlined } from '@ant-design/icons';
import { getPosIDs, getTenantID, getUserDepID, getUserID } from '@/utils';
import { getUpdateConfig } from '../mconfig/UpdateConfig';
import { connect, history } from 'umi';
import { Col, Form, Row, Spin, message, Tabs, Modal, Space, Button } from 'antd';
import React from 'react';
import { ILoadMapTypeAll } from '@/common';
import { WorkflowChedkRecord, WorkflowNoDefaultTable, WorkflowSwitchModal } from '@/components/WorkflowCommonCopy';
import { orderType, requestController } from '../common/Format';
import '../common/style.less';
import { getUserDataList } from '@/services/BaseLayout';
import { addStorageService, approvedAssetApplyUseSerivice, editStorageService, getDetailService } from '../services';
import { useAllotManageReducer, TransferManageContext, IAllotActionEnum } from '../mconfig';
import { OpenMaterialModal } from '../mconfig/OpenMaterialModal';
import { DetailInfoViewBottomBtn } from '../mconfig/DetailInfoViewBottomBtn';
import { RevokeModal } from '../../Acomponents/RevokeModal';
import moment from 'moment';
import { OpenReadAssetModal } from '../../Assetmanagement/UseAsReturn/mconfig/OpenReadAssetModal';

const UpdataMaterialModal: React.FC<any> = ({ curRes, locationProps }) => {
  /** 样式根目录 */
  const styleFixCls = 'contract-styfixcls-';

  const { materielList, allotDispatch } = useAllotManageReducer();

  /** 表单 */
  const [contractForm] = Form.useForm();
  const [saveFlag, setSaveFlag] = useState<boolean>(false);
  // 详情数据
  const [detailInfo, setDetailInfo] = useState<any>({});
  /** 选中的单位ID */
  const [selectUserInfo, setSelectUserInfo] = useState<Record<string, any>>({});
  /** 打开选择材料列表 */
  const [openMaterialModal, setOpenMaterialModal] = useState<boolean>(false);
  // 弹窗部门id
  const [departId, setDepartId] = useState<any>('');
  /** 调剂审批同意判断是否可以调用同步接口 */
  const [auditSuccessState, setAuditSuccessState] = useState(false);
  /** 打开查看资产列表 */
  const [openReadAssetModal, setOpenReadAssetModal] = useState<Record<string, any>>({});
  /**是否显示撤销弹窗*/
  const [invalidState, setInvalidState] = useState<Record<string, any>>({}); /**撤销弹窗*/

  // 工作流
  const [isShowWorkRecord, setIsShowWorkRecord] = useState<boolean>(false);
  const [showSwitchFlow, setShowSwitchFlow] = useState<boolean>(false);
  const [workFlowInfoObj, setWorkFlowInfoObj] = useState<Record<string, any>>({
    selectFlowRows: {},
    showWorkFlowModal: false,
    saveNoDefaultFlowID: '',
  });

  const openMaterialModalStatus = () => {
    const A = config.form.getFieldValue('originalDepartmentID');
    const B = config.form.getFieldValue('allotType');
    let obj: Record<string, any> = {};
    if (B == 3 && A) {
      obj.assetDepartmentID = A;
      obj.assetState = `${getTenantID()}${ILoadMapTypeAll.ASSET_STATUS}1001`;
    } else {
      obj.useDepartmentID = A;
    }
    if (A) {
      setDepartId(obj);
      setOpenMaterialModal(true);
    } else {
      message.warning('请先选择移交使用部门！');
    }
  };

  /**
   * 新增编辑回调
   * @param res 接口返回数据
   * @param callType true 为新增回调  || false 为编辑回调
   */
  const updateAnnounceCallback = (res: any) => {
    if (res && res?.msgFlag) {
      // flag 表示点击的提交
      if (saveFlag) {
        setWorkFlowInfoObj({
          selectFlowRows: res?.obj,
          showWorkFlowModal: true,
          saveNoDefaultFlowID: '',
        });
      } else {
        message.success(res?.msg);
        history.push({
          pathname: '/assetTransferController/manage',
          state: {
            delRouterNameSource: history.location.pathname,
          },
        });
      }
    } else {
      message.error(res?.msg);
    }
  };

  // 获取详情回调
  const updataGetDetail = (res: any) => {
    if (res && res?.msgFlag) {
      const {
        obj: { massetApplyNumberList },
      } = res;
      message.success(res.msg || '获取详情成功');
      // 详情数据
      setDetailInfo(res?.obj);
      if (res?.obj?.newDepartmentID) {
        getUserRun({
          //获取当前使用部门用户信息
          userDepartmentID: res?.obj?.newDepartmentID,
        });
      }
      allotDispatch({
        type: IAllotActionEnum.SELECT_MATERIEL,
        payload: massetApplyNumberList,
      });

      /** 是否是审核中 */
      if (
        res?.obj?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1000` &&
        res?.obj?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_TRANS_STATUS}1001`
      ) {
        setAuditSuccessState(true);
      }
    } else {
      message.error(res.msg || '获取详情失败');
    }
  };

  /** 获取当前部门用户数据 */
  const { getUserRun, getUserLoading, getUserList } = getUserDataList((res: any) => {
    if (!(res && res?.msgFlag)) {
      message.error(res?.msg);
    }
  });

  /** 获取当前部门用户数据 */
  const changeGetUser = (value: string | number) => {
    contractForm?.setFieldValue('newerID', undefined);
    getUserRun({
      //获取当前使用部门用户信息
      userDepartmentID: value,
    });
  };

  /** 获取当前人对象 */
  const getSelectUserInfo = (value: string | number, option: any) => {
    setSelectUserInfo(option);
  };

  // 新增 暂存
  const { addStorageLoading, addStorageRun } = addStorageService(updateAnnounceCallback);
  // 修改 编辑
  const { editStorageLoading, editStorageRun } = editStorageService(updateAnnounceCallback);
  // 获取详情
  const { getDetailLoading, getDetailRun } = getDetailService(updataGetDetail);
  /** 调剂-最后一个人审核通过后调用的同步接口 */
  const { approvedAssetApplyUseRun, approvedAssetApplyUseLoading } = approvedAssetApplyUseSerivice((res) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      // history.push({
      //   pathname: '/assetTransferController/manage',
      //   state: {
      //     delRouterNameSource: history.location.pathname,
      //   },
      // });
    } else {
      message.error(res?.msg);
    }
  });

  // 打开查看我的资产列表方法
  const openReadAssetModalFun = (userID) => {
    setOpenReadAssetModal({
      isShow: true,
      userID,
    });
  };

  /** 获取表单配置
   *  @leftSelectName    左侧仓库名称
   *  @record   当前项
   */
  const { config, methods } = getUpdateConfig({
    pageType: locationProps.state.pageType,
    record: locationProps?.state?.record ? locationProps?.state?.record : {},
    detailInfo,
    contractForm,
    changeGetUser,
    getUserLoading,
    getUserList,
    getSelectUserInfo,
    openMaterialModalStatus,
    openReadAssetModalFun,
  });

  // 暂存按钮
  const handleSave = (flag: boolean) => {
    // 对表单进行校验，获取表单数据
    config.form.validateFields()?.then((values: any) => {
      // 组装数据
      let params = {
        ...values,
        createTime: moment(values?.createTime).format('YYYY-MM-DD HH:mm:ss'), // 申请日期
        originalDepartmentID: getUserDepID(), // 移交使用部门
        newDepartmentID: values.allotType == 1 ? getUserDepID() : values.newDepartmentID, // 接收使用部门
        massetApplyNumberList: materielList,
        newCompanyID: selectUserInfo?.userCompanyID ? selectUserInfo?.userCompanyID : '',
        newPositionID: selectUserInfo?.userPositionID ? selectUserInfo?.userPositionID : '',
        // createTime: values?.createTime.format('YYYY-MM-DD HH:mm:ss'),
      };

      setSaveFlag(flag);
      // 新增和修改接口
      if (locationProps?.state?.pageType == 'add') {
        addStorageRun(params);
      } else {
        params.id = locationProps?.state?.record?.id; // 修改 id
        let obj = {
          ...detailInfo,
          ...params,
        };
        editStorageRun(obj);
      }
    });
  };

  /**
   * 关闭切换流程modal方法
   * @isDefaultModal  点击确定 true,关闭切换流程zujian,打开发起流程组件  点击取消 false 关闭切换流程组件
   */
  const closeSwitchFlowModal = (isDefaultModal: boolean) => {
    if (isDefaultModal) {
      setWorkFlowInfoObj({
        ...workFlowInfoObj,
        showWorkFlowModal: true,
      });
    } else {
      setShowSwitchFlow(false);
    }
  };

  /**
   * 处理工作流功能 权限
   */
  const workflowPowerAllBtn = useMemo(() => {
    let pownerBtn: Record<string, any> = {
      revokeFlagBtn: false, //撤销按钮
      invalBoolBtn: false, //暂停开始按钮
      stopProcInstBtn: false, //流程作废接口
    };
    if (detailInfo?.state == `${getTenantID()}${ILoadMapTypeAll?.DISCLOSURE_STATE}1001`) {
      pownerBtn['revokeFlagBtn'] = true;
      pownerBtn['stopProcInstBtn'] = true;
    }

    const taskType: string = `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1001`;
    const taskHandInfo: Record<string, any> = detailInfo?.paramObject?.[taskType];
    if (
      taskHandInfo &&
      taskHandInfo?.mactivitiTaskList?.length > 0 &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneePositionID == getPosIDs() &&
      taskHandInfo?.mactivitiTaskList?.[0]?.assigneeID == getUserID()
    ) {
      pownerBtn['invalBoolBtn'] = true;
    }
    return pownerBtn;
  }, [detailInfo]);

  // 获取详情
  useEffect(() => {
    if (locationProps?.state?.pageType != 'add') {
      getDetailRun(locationProps?.state?.record?.id);
    }
  }, []);

  /** 申请页ref */
  const { confirm } = Modal;

  /** 关闭当前页 */
  const handleClose = () => {
    confirm({
      title: '关闭',
      icon: <QuestionCircleOutlined />,
      content: '确定要关闭当前页吗？',
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        history.push({
          pathname: locationProps?.state?.returnPathName,
          state: {
            delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
            returnPathName: locationProps?.state?.returnPathName,
          },
        });
      },
      onCancel() {},
    });
  };

  /** 监听审核状态 */
  useEffect(() => {
    if (
      auditSuccessState &&
      detailInfo?.checkState === `${getTenantID()}${ILoadMapTypeAll.ALLFLOW_CHECKRESULT}1002` &&
      detailInfo?.state === `${getTenantID()}${ILoadMapTypeAll.STORAGE_TRANS_STATUS}1003`
    ) {
      approvedAssetApplyUseRun({ ...detailInfo, workflowResult: true });
    }
  }, [detailInfo?.checkState, detailInfo?.state, auditSuccessState]);

  const changeRevoke = () => {
    setInvalidState({
      isShow: true,
      resObj: detailInfo,
    });
  };

  /** tabs 标签页操作 */
  const contactsTabsExtra = () => {
    return (
      <DetailInfoViewBottomBtn
        position="top"
        changeRevoke={changeRevoke}
        detailInfo={detailInfo}
        getDetailRun={getDetailRun}
        locationProps={locationProps}
        handleSave={handleSave}
      />
    );
  };

  /** 返回tab子页面 */
  const tabsItem = () => {
    let items: any[] = [
      {
        label: '申请详情',
        key: '001',
        children: (
          <div className="commonTabsBodyDom">
            <div className={Cls('tabsBodyInfoDom', `${styleFixCls}updateFormBox`)}>
              <ScrollBarLayout style={{ padding: '5px 20px' }}>
                <DescriptionsType config={config} />
              </ScrollBarLayout>
            </div>
            <div className="tabsBodyBottomBtn">
              <Space>
                <>
                  {/* {locationProps?.state?.pageType !== 'detail' || (detailInfo?.state == '100124141000' && detailInfo?.checkState == '100199021003') ? (
                    <Button type={'primary'} icon={<SaveOutlined />} onClick={() => handleSave(false)}>
                      暂存
                    </Button>
                  ) : null} */}
                  {((!detailInfo?.state ||
                    (detailInfo?.state == '100124141000' && !detailInfo?.checkState) ||
                    (detailInfo?.state == '100124141002' && detailInfo?.checkState == '100199021003')) &&
                    detailInfo?.createrID == getUserID()) ||
                  locationProps?.state?.pageType === 'add' ? (
                    <Button
                      type={'primary'}
                      // icon={<CheckCircleOutlined />}
                      onClick={() => handleSave(true)}
                    >
                      提交
                    </Button>
                  ) : null}
                  <Button danger onClick={handleClose}>
                    关闭
                  </Button>
                </>
                {/* 流程节点弹框 */}
                {/* {locationProps?.state?.pageType == 'detail' ? (
                  <WorkflowHndTaskBtn
                    flowDetailInfo={detailInfo}
                    reloadCallback={() => {
                      getDetailRun(detailInfo?.id);
                    }}
                    requestController={'assetApplyAllot'}
                    flowBusinessType={BGflowBusinessType()}
                  />
                ) : null} */}
              </Space>
            </div>
          </div>
        ),
      },
    ];
    return items;
  };

  return (
    <TransferManageContext.Provider
      value={{
        rightTableProps: {
          dataSource: [],
          materielForm: {},
          loading: false,
          getAcquisitionTableData: ({}) => {},
          mapList: [],
          pagination: {},
          otherParams: {},
          searchList: [],
          reloadTableData: () => {},
        },
        materielList,
        curRes,
        allotDispatch,
      }}
    >
      <div className={'applyAssetTransfer-update-UpdataIntentBox'}>
        <Spin spinning={addStorageLoading || editStorageLoading || getDetailLoading}>
          <Row className={`${styleFixCls}row`}>
            <Col span={24} className={`${styleFixCls}row-col`}>
              <Tabs
                className={pageStyles['commonTabs']}
                type="card"
                onChange={(activeKey: string) => {}}
                items={tabsItem()}
                destroyInactiveTabPane={true}
                tabBarExtraContent={contactsTabsExtra()}
              />
            </Col>
          </Row>

          {/* 查看资产列表弹窗组件 */}
          {openReadAssetModal?.isShow && (
            <OpenReadAssetModal
              curRes={curRes}
              onClose={() => {
                setOpenReadAssetModal({});
              }}
              userID={openReadAssetModal?.userID}
            />
          )}

          {/* 选择材料列表 */}
          {openMaterialModal && (
            <OpenMaterialModal
              isShowModal={openMaterialModal}
              departmentID={departId}
              onClose={() => {
                setOpenMaterialModal(false);
              }}
            />
          )}

          {/* 工作流-----审批记录 */}
          {detailInfo?.paramObject?.[`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1012`] && (
            <WorkflowChedkRecord
              curRes={curRes}
              dataDetailInfo={detailInfo}
              flowBusinessType={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1012`}
              requestController={requestController()}
              reloadPageCallback={() => {
                getDetailRun({ id: detailInfo?.id });
              }} // 刷新方法-详情方法
              revokeStateID={`${getTenantID()}${ILoadMapTypeAll?.STORAGE_TRANS_STATUS}1000`}
              allBtnFuncQuqry={workflowPowerAllBtn}
              tabPaneHeight={0.35}
              isCheckDrawer={true}
              isShowCollapse={isShowWorkRecord}
              changeCollapse={(val) => {
                setIsShowWorkRecord(val);
              }}
              cancelStateId={`${getTenantID()}${ILoadMapTypeAll?.STORAGE_TRANS_STATUS}1004`}
              isSyncArchive={true}
            />
          )}

          {/* 工作流-----发起流程审批弹窗 */}
          {workFlowInfoObj?.showWorkFlowModal && (
            <WorkflowSwitchModal
              openVisible={workFlowInfoObj?.showWorkFlowModal}
              businessInfoObj={workFlowInfoObj?.selectFlowRows}
              requestController={requestController()}
              orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
              category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1012`}
              businessCategory={``}
              selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
              reloadInfoCallback={() => {
                history.push({
                  pathname: '/assetTransferController/manage',
                  state: {
                    delRouterNameSource: history.location.pathname,
                  },
                });
              }}
              openFlowChangeModal={setShowSwitchFlow}
              onClose={() => {
                setWorkFlowInfoObj({
                  ...workFlowInfoObj,
                  showWorkFlowModal: false,
                });
                history.push({
                  pathname: '/assetTransferController/manage',
                  state: {
                    delRouterNameSource: history.location.pathname,
                  },
                });
              }}
              replaceStrObj={{ own: 'own', workflowType: 'category' }}
            />
          )}

          {/* 撤销弹窗 */}
          {/* {invalidState?.isShow && (
            <RevokeModal
              resObj={invalidState?.resObj}
              revokeRequestUrl={'/assetApplyAllot/revoke'}
              onClose={() => setInvalidState({})}
              reqBody={{ id: invalidState?.resObj?.id, state: `${getTenantID()}${ILoadMapTypeAll?.STORAGE_TRANS_STATUS}1000` }}
              modalTip={
                <div style={{ color: '#000' }}>
                  确认是否撤销【<span style={{ color: 'red' }}>{invalidState?.resObj?.applyTitle}</span>】的审核, 撤销后可重新提交！
                </div>
              }
              reloadRequest={() => {
                history.push({
                  pathname: locationProps?.state?.returnPathName,
                  state: {
                    delRouterNameSource: history.location.pathname, //必传,要删除的路由名称
                    returnPathName: locationProps?.state?.returnPathName,
                  },
                });
              }}
            />
          )} */}

          {/* 挑选流程组件 */}
          {showSwitchFlow && (
            <WorkflowNoDefaultTable
              openVisibleSwitch={showSwitchFlow}
              onCloseSwitch={closeSwitchFlowModal}
              requestController={'purchaseSourceIntentController'}
              orderType={workFlowInfoObj?.selectFlowRows?.orderType || orderType()}
              category={`${getTenantID()}${ILoadMapTypeAll.ALLFLOW_TYPE}1012`}
              businessCategory={``}
              saveSelectFlowID={(flowId: string) => {
                setWorkFlowInfoObj({
                  ...workFlowInfoObj,
                  saveNoDefaultFlowID: flowId,
                });
              }}
              selectFlowID={workFlowInfoObj?.saveNoDefaultFlowID}
            />
          )}
        </Spin>
      </div>
    </TransferManageContext.Provider>
  );
};

export default connect(({ baseLogin, navTab }: Record<string, any>) => ({
  curRes: baseLogin?.permissions,
  navTab,
}))(UpdataMaterialModal);
